package com.corpcredit.webapp.action;

import java.io.Serializable;
import java.util.Date;

import com.corpcredit.Constants;
import com.corpcredit.model.Cpxs;
import com.corpcredit.model.Jbqk;
import com.corpcredit.webapp.action.BasePage;
import com.corpcredit.service.GenericManager;

public class CpxsForm extends BasePage implements Serializable {
    private GenericManager<Cpxs, Long> cpxsManager;
    private Cpxs cpxs = new Cpxs();
    private Long id;
    
    private Jbqk jbqk;

    public void setJbqk( Jbqk jbqk )
    {
        this.jbqk = jbqk;
    }

    public void setCpxsManager(GenericManager<Cpxs, Long> cpxsManager) {
        this.cpxsManager = cpxsManager;
    }

    public Cpxs getCpxs() {
        return cpxs;
    }

    public void setCpxs(Cpxs cpxs) {
        this.cpxs = cpxs;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String delete() {
        cpxsManager.remove(cpxs.getId());
        addMessage("cpxs.deleted");

        return "list";
    }

    public String edit() {
        // Comparison to zero (vs. null) is required with MyFaces 1.2.2, not with previous versions
        if (id != null && id != 0) {
            cpxs = cpxsManager.get(id);
        } else {
            cpxs = new Cpxs();
        }

        return "edit";
    }

    public String save() {
        boolean isNew = (cpxs.getId() == null || cpxs.getId() == 0);
        // set the related jbqk as a foreign key.
        cpxs.setJbqk( jbqk );
        // set username who act this operation, get the user name from httprequest
        cpxs.setUsername( getRequest().getRemoteUser() );
        // set operation date using the current time
        cpxs.setOptdate( new Date() );
        // set the operation type, default two types: add and update
        cpxs.setOperation( (isNew) ? Constants.OPERATION_ADD : Constants.OPERATION_UPDATE );
        cpxsManager.save(cpxs);

        String key = (isNew) ? "cpxs.added" : "cpxs.updated";
        addMessage(key);

        if (isNew) {
            return "list";
        } else {
            // set the id to the next page
            this.id = cpxs.getId();
            // return the update confirmation page
            return edit();
        }
    }
} 